const dotenv = require('dotenv')
const path = require('path')

// 加载环境变量
dotenv.config()

const config = {
  // 服务器配置
  server: {
    port: process.env.PORT || 806,
    host: process.env.HOST || 'localhost',
    env: process.env.NODE_ENV || 'development'
  },

  // JWT配置
  jwt: {
    secret: process.env.JWT_SECRET || 'default-secret-key',
    expiresIn: process.env.JWT_EXPIRES_IN || '24h',
    refreshSecret: process.env.JWT_REFRESH_SECRET || 'default-refresh-secret-key',
    refreshExpiresIn: process.env.JWT_REFRESH_EXPIRES_IN || '7d',
    issuer: process.env.JWT_ISSUER || 'qdkj-course-backend',
    audience: process.env.JWT_AUDIENCE || 'qdkj-course-frontend'
  },

  // 加密配置
  encryption: {
    key: process.env.ENCRYPTION_KEY || 'default-32-character-key-change-me'
  },

  // 数据库配置
  database: {
    type: process.env.DB_TYPE || 'json',
    path: process.env.DB_PATH || './db.json'
  },

  // 日志配置
  logging: {
    level: process.env.LOG_LEVEL || 'info',
    file: process.env.LOG_FILE || './logs/app.log'
  },

  // AI服务配置
  ai: {
    defaultBaseUrl: process.env.DEFAULT_AI_BASE_URL || 'https://api.siliconflow.cn/v1',
    defaultModel: process.env.DEFAULT_AI_MODEL || 'deepseek-ai/DeepSeek-V2.5'
  },

  // 安全配置
  security: {
    rateLimitWindowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 900000, // 15分钟
    rateLimitMaxRequests: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || 100
  },

  // CORS配置
  cors: {
    origin: process.env.CORS_ORIGIN || 'http://localhost:5173'
  }
}

// 验证必要的配置
function validateConfig() {
  const requiredConfigs = [
    'jwt.secret',
    'encryption.key'
  ]

  for (const configPath of requiredConfigs) {
    const value = configPath.split('.').reduce((obj, key) => obj[key], config)
    if (!value || value.includes('default') || value.includes('change')) {
      console.warn(`⚠️  警告: ${configPath} 使用默认值，生产环境请修改`)
    }
  }
}

// 开发环境下验证配置
if (config.server.env === 'development') {
  validateConfig()
}

module.exports = config
module.exports.validateConfig = validateConfig